package com.example.app;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MainActivity extends AppCompatActivity implements HomeMenuItemAdapter.OnMenuItemClickListener{
    private final Map<String, String> kw = new HashMap<>();
    // 主菜单
    private final List<HomeMenuItem> homeList = new ArrayList<>();
    public final List<NewsItem> newsList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        initkw();
        // 初始化菜单
        initMenus();
        // 初始化新闻列表
        fetchNews("Business");
        Log.d("HOME", "data get ready");
        // 主页菜单
        RecyclerView menuRecyclerView = findViewById(R.id.home_menu);
        HomeMenuItemAdapter menuItemAdapter = new HomeMenuItemAdapter(homeList);
        menuRecyclerView.setAdapter(menuItemAdapter);
        menuItemAdapter.setOnMenuItemClickListener(this);
    }
    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onMenuItemClick(int position){
        HomeMenuItem selectedItem = homeList.get(position);
        fetchNews(selectedItem.name);
        Log.d("menu", selectedItem.name);
    }
    private void initkw(){
        kw.put("Business", "caijing");
        kw.put("Entertainment", "yule");
        kw.put("Health", "jiankang");
        kw.put("Science", "keji");
        kw.put("Sports", "tiyu");
    }
    private void initMenus() {
        homeList.add(new HomeMenuItem("Business", R.drawable.business));
        homeList.add(new HomeMenuItem("Entertainment", R.drawable.entertainment));
        homeList.add(new HomeMenuItem("Health", R.drawable.health));
        homeList.add(new HomeMenuItem("Science", R.drawable.science));
        homeList.add(new HomeMenuItem("Sports", R.drawable.sports));
    }

    private void fetchNews(String keyword) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<List<NewsItem>> futureTask = executor.submit(() -> {
            try {
                List<NewsItem> resultNewsList = new ArrayList<>();
                String jsonResponse = getJSON(kw.get(keyword));
                if (jsonResponse != null) {
                    JSONObject jsonObject = new JSONObject(jsonResponse);
                    JSONObject result = jsonObject.getJSONObject("result");
                    JSONArray articles = result.getJSONArray("data");
                    // 添加文章
                    for (int i = 0; i < articles.length() && i < 20; i++) {
                        JSONObject article = articles.getJSONObject(i);
                        String name = article.getString("title");
                        String author = article.getString("author_name");
                        String url = article.getString("url");
                        String time = article.getString("date");
                        String pic = article.getString("thumbnail_pic_s");
                        Log.d("title", name);
                        resultNewsList.add(new NewsItem(name, author, url, time, pic));
                    }
                    return resultNewsList;
                }
            } catch (Exception e) {
                Log.e("FetchNewsTask", "Error fetching news. Retrying...");
            }
            return null;
        });
        try {
            List<NewsItem> result = futureTask.get();
            if (result != null && !result.isEmpty()) {
                newsList.clear();
                newsList.addAll(result);
                // 更新RecyclerView
                runOnUiThread(() -> {
                    RecyclerView newsListRecyclerView = findViewById(R.id.news_list);
                    NewsItemAdapter newsItemAdapter = new NewsItemAdapter(newsList);
                    newsListRecyclerView.setAdapter(newsItemAdapter);
                });
            }
        } catch (Exception ignored) {
        }

        executor.shutdown();
    }

    private String getJSON(String keyword) {
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        BufferedReader read = null;
        String jsonResponse = null;
        // 获取url
        String urlWeb = "https://v.juhe.cn/toutiao/index";
        Map<String, String> params = new HashMap<>();
        String API_KEY = "91ffd1baaebebfaed0f93423a77f9fdc";
        params.put("key", API_KEY);
        params.put("type", keyword);
        String paramStr = urlencode(params);
        try {
            urlWeb += "?"+paramStr;
            URL url = new URL(urlWeb);
            Log.d("GET", "create success");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(15000);
            urlConnection.setReadTimeout(60000);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 发送请求
            urlConnection.connect();
            Log.d("GET", "connect success");
            // 通过connection连接，获取输入流
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                read = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = read.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                jsonResponse = sbf.toString();
            }
        } catch (Exception ignored) {
        }  finally {
            // 关闭资源
            if (null != read) {
                try {
                    read.close();
                } catch (IOException ignored) {
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();// 关闭远程连接
            }
        }
        return jsonResponse;
    }
    public String urlencode(Map<String, String> data){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException ignored) {
            }
        }
        return sb.toString();
    }
}
